package com.example.camproject

import android.Manifest
import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Network
import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import com.example.camproject.network.NetClient
import com.example.camproject.network.User
import com.google.gson.Gson
import retrofit2.Call
import retrofit2.Response
import android.provider.MediaStore
import android.graphics.Bitmap
import androidx.core.app.ActivityCompat
import com.example.camproject.network.Data
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import retrofit2.http.Multipart
import java.io.File
import okhttp3.RequestBody
import retrofit2.Callback


class LoginActivity : AppCompatActivity() {
    lateinit var username:EditText
    lateinit var password:EditText
    lateinit var upload:ImageView
    lateinit var login:Button
    lateinit var register:Button
    var bitmap:Bitmap?=null
    private val imgName="avata.jpg"

    override fun onCreate(savedInstanceState : Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        username=findViewById(R.id.user)
        password=findViewById(R.id.pwd)
        upload=findViewById(R.id.upload)
        login=findViewById(R.id.login)
        register=findViewById(R.id.register)


        upload.setOnClickListener {
            reqPermissions()
            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            startActivityForResult(intent , 100)
        }

        login.setOnClickListener {
            if (upload.visibility==ImageView.VISIBLE){
                Toast.makeText(this,"请点击注册按钮", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            var text1=username.text
            var text2=password.text
            if (text1.isEmpty()|| text2.isEmpty()){
                Toast.makeText(this,"你输入的用户名或者密码为空", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            var map1= mapOf("username" to text1.toString())
            var res=NetClient.apis.login(map1)
            res.enqueue(object :retrofit2.Callback<User>{
                override fun onResponse(call : Call<User> , response : Response<User>) {
                    var code=response.body()?.code
                    if (code==200){
                        val data=response.body()?.data
                        backHome(data as Data)
                    }else{
                        Toast.makeText(this@LoginActivity,"你的密码或者用户名错误", Toast.LENGTH_SHORT).show()
                    }
                }

                override fun onFailure(call : Call<User> , t : Throwable) {
                    Toast.makeText(this@LoginActivity,"network error", Toast.LENGTH_SHORT).show()
                }

            })
        }

        register.setOnClickListener {
            var text1=username.text
            var text2=password.text
            if (text1.isEmpty()|| text2.isEmpty()){
                Toast.makeText(this,"你输入的用户名或者密码为空", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (upload.visibility==ImageView.VISIBLE){
                //
                uploadRegister(text1.toString(),text2.toString())
                Toast.makeText(this,"正在上传，完成后自动跳转", Toast.LENGTH_LONG).show()
                var intent=Intent(this@LoginActivity,MainActivity::class.java)
                startActivity(intent)
            }else{
                Toast.makeText(this,"来上传头像吧", Toast.LENGTH_SHORT).show()
                upload.visibility=ImageView.VISIBLE
            }
        }
    }

    fun reqPermissions(){
        var permission = listOf(
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
        )
        permission.forEach {
            if (ActivityCompat.checkSelfPermission(this,
                    it
                ) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions( this, arrayOf(it),100)
            }
            }
    }

    fun uploadRegister(username:String,password:String){
        val builder : MultipartBody.Builder = MultipartBody.Builder()
            .setType(MultipartBody.FORM) //在这里添加服务器除了文件之外的其他参数
            .addFormDataPart("username" , username)
            .addFormDataPart("password" , password)

        var file1Location=this.getFilesDir().toString() + "/images/"+imgName
        val file = File(file1Location)
        val imageBody : RequestBody = RequestBody.create(
            "multipart/form-data".toMediaTypeOrNull() ,
            file
        )
        //添加文件(uploadfile就是你服务器中需要的文件参数)
        builder.addFormDataPart("faceImg" , file.name , imageBody)
        val parts= builder.build().parts
        NetClient.apis.createUser(parts).enqueue(object:Callback<User>{
            override fun onResponse(call : Call<User> , response : Response<User>) {
                var res=response.body()
                if (res!=null && res.code==200){
                    backHome(res.data)
                }
            }

            override fun onFailure(call : Call<User> , t : Throwable) {
                Toast.makeText(this@LoginActivity,"network error", Toast.LENGTH_SHORT).show()
            }

        })
    }

    fun backHome(data:Data){
        var gson=Gson()
        var udb=getSharedPreferences("userinfo", MODE_PRIVATE)
        var edi=udb.edit()
        edi.putString("user",gson.toJson(data))
        edi.commit()
        var intent=Intent(this@LoginActivity,MainActivity::class.java)
        startActivity(intent)
    }

    override fun onActivityResult(requestCode : Int , resultCode : Int , data : Intent?) {
        super.onActivityResult(requestCode , resultCode , data)
        val extras = data?.extras
        var bitmap=extras?.get("data")
        println(bitmap.toString())
        if (bitmap!=null){
            var progressdig=ProgressDialog(this@LoginActivity)
            progressdig.setTitle("提示")
            progressdig.setMessage("正在准备上传图片")
            progressdig.setCancelable(false)
            progressdig.show()
            BitmapUtils.saveBitmap(imgName,bitmap as Bitmap,this@LoginActivity)
            progressdig.dismiss()
            upload.setImageBitmap(bitmap)
        }else{
            println("else")
        }
    }
}







